<template>
  <el-dialog
    v-model="dialogVisible"
    class="layer-publish-dialog"
    title="图层发布"
    width="600px"
    draggable
    :before-close="closeDialog"
  >
    <el-form
      ref="layerPublishFormRef"
      :model="publishLayerForm"
      label-width="auto"
      :rules="rules"
      style="max-width: 600px"
      label-position="left"
    >
      <el-form-item label="工作空间 :">
        <el-select
          v-model="workspaceName"
          filterable
          clearable
          @change="workspaceChangeHandler"
          placeholder="请选择工作空间"
        >
          <el-option
            v-for="workspaceItem in workspaceList"
            :key="workspaceItem.name"
            :label="workspaceItem.name"
            :value="workspaceItem.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据存储 :">
        <el-select
          v-model="dataStoreName"
          filterable
          clearable
          @change="dataStoreChangeHandler"
          placeholder="请选择数据存储"
        >
          <el-option
            v-for="dataStoreItem in dataStoreList"
            :key="dataStoreItem"
            :label="dataStoreItem"
            :value="dataStoreItem"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="特征表 :">
        <el-select
          v-model="publishLayerForm.nativeName"
          filterable
          clearable
          @change="initFeatureType"
          placeholder="请选择特征表"
        >
          <el-option
            v-for="featureTypeName in storeFeatureTypes"
            :key="featureTypeName"
            :label="featureTypeName"
            :value="featureTypeName"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="图层名称 :" prop="name">
        <!-- 此处只允许输入英文字母 -->
        <el-input
          v-model="publishLayerForm.name"
          placeholder="请输入英文或字母名称"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="标题 :" prop="title">
        <el-input v-model="publishLayerForm.title" placeholder="请输入标题" maxlength="20" />
      </el-form-item>
      <el-form-item label="摘要 :" prop="abstract">
        <el-input v-model="publishLayerForm.abstract" placeholder="请输入摘要" maxlength="20" />
      </el-form-item>
      <el-form-item label="原始投影 :" prop="nativeCRS">
        <el-input
          v-model="publishLayerForm.nativeCRS"
          placeholder="请输入原始坐标系"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="定义投影 :" prop="srs">
        <el-input v-model="publishLayerForm.srs" placeholder="请输入要定义的投影" />
      </el-form-item>
      <el-form-item label="投影处理 :">
        <el-select v-model="publishLayerForm.projectionPolicy" clearable placeholder="请选择特征表">
          <el-option label="强制声明" value="FORCE_DECLARED" />
          <el-option label="重投影" value="REPROJECT_TO_DECLARED" />
          <el-option label="保持原投影" value="NONE" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="publishLayer">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, reactive, ref, toRef, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useLayerPublishModal } from '../hooks'
import { restHelperInstance } from '@/composables/useGeoHelper'
import type { IDatastore, ILayer } from 'geoserver-helper/interface'
import useWorkspaceModal from '@/composables/useWorkspace'

const workspaceModal = useWorkspaceModal()
const workspaceList = workspaceModal.workspaceList
//数据存储列表
const dataStoreList = ref<string[]>([])
//当前数据存储下的特征表列表
const storeFeatureTypes = ref<string[]>([])

// 图层发布相关hook
const layerPublishModal = useLayerPublishModal()
// 表单ref
const layerPublishFormRef = ref<FormInstance>()
//工作空间名称
const workspaceName = ref('')
//数据存储名称
const dataStoreName = ref('')
//图层新增表单
const publishLayerForm = ref<ILayer.FeatureTypeAddParam>({
  name: '',
  title: '',
  abstract: '',
  nativeName: '',
  nativeCRS: '',
  srs: 'EPSG:4326',
})

const rules = reactive<FormRules<ILayer.FeatureTypeAddParam>>({
  name: [{ required: true, trigger: 'blur' }],
  nativeCRS: [{ required: true, trigger: 'blur' }],
})

//当前图层详情
const currentLayerInfo = ref<ILayer.LayerSourceDetailInfo>({})
const mapUrl = import.meta.env.VITE_MAP_SERVER_URL
interface emitInterface {
  (e: 'updateLayers'): void
}
const emit = defineEmits<emitInterface>()
const dialogVisible = layerPublishModal.publishLayerVisible

const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}

/**
 * @description: 工作空间下拉改变事件
 */
const workspaceChangeHandler = () => {
  let promiseArray: Promise<
    boolean | IDatastore.ResDatastoreList | IDatastore.ResCoveragestoreList
  >[] = [
    restHelperInstance.getDatastoreListApi(workspaceName.value),
    restHelperInstance.getCoveragestoresListApi(workspaceName.value),
  ].map((item) => item.catch(() => Promise.resolve(true)))
  dataStoreList.value = []
  dataStoreName.value = ''
  Promise.all(promiseArray)
    .then((res) => {
      res.forEach((singleDatastoreList) => {
        if (typeof singleDatastoreList !== 'boolean') {
          if (
            (singleDatastoreList as IDatastore.ResDatastoreList).dataStores &&
            (singleDatastoreList as IDatastore.ResDatastoreList).dataStores.dataStore
          ) {
            const currentDatastore = singleDatastoreList as IDatastore.ResDatastoreList
            if (currentDatastore.dataStores.dataStore instanceof Array) {
              currentDatastore.dataStores.dataStore.forEach((singleDatastore) => {
                dataStoreList.value.push(singleDatastore.name)
              })
            }
          } else if (
            (singleDatastoreList as IDatastore.ResCoveragestoreList).coverageStores &&
            (singleDatastoreList as IDatastore.ResCoveragestoreList).coverageStores.coverageStore
          ) {
            const currentDatastore = singleDatastoreList as IDatastore.ResCoveragestoreList
            if (currentDatastore.coverageStores.coverageStore instanceof Array) {
              currentDatastore.coverageStores.coverageStore.forEach((singleDatastore) => {
                dataStoreList.value.push(singleDatastore.name)
              })
            }
          }
        }
      })
    })
    .catch(() => {
      ElMessage.error('获取工作空间列表失败')
    })
}

/**
 * @description: 数据存储变更事件
 * @return {*}
 */
const dataStoreChangeHandler = () => {
  if (workspaceName.value && dataStoreName.value) {
    restHelperInstance
      .getFeaturetypesApi(workspaceName.value, dataStoreName.value, 'available')
      .then((res) => {
        if (res.list && res.list.string) {
          storeFeatureTypes.value = res.list.string
        }
      })
      .catch(() => {
        ElMessage.error('获取特征列表失败')
      })
  }
}
/**
 * @description: 发布图层
 * @return {*}
 */
const publishLayer = () => {
  if (!layerPublishFormRef.value) return
  layerPublishFormRef.value.validate((valid) => {
    if (valid) {
      restHelperInstance
        .creatFeaturetypeApi(workspaceName.value, dataStoreName.value, publishLayerForm.value)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '添加成功',
          })
          closeDialog()
          emit('updateLayers')
        })
        .catch(() => {
          ElMessage({
            type: 'error',
            message: '添加失败！请检查参数是否符合要求',
          })
        })
    }
  })
}

const initFeatureType = () => {
  publishLayerForm.value.name = ''
  publishLayerForm.value.title = ''
  publishLayerForm.value.abstract = ''
  publishLayerForm.value.nativeName = ''
  publishLayerForm.value.nativeCRS = ''
  publishLayerForm.value.srs = 'EPSG:4326'
}
/**
 * @description: 重置表单
 * @return {*}
 */
const resetForm = () => {
  publishLayerForm.value.name = ''
  publishLayerForm.value.title = ''
  publishLayerForm.value.abstract = ''
  publishLayerForm.value.nativeName = ''
  publishLayerForm.value.nativeCRS = ''
  publishLayerForm.value.srs = 'EPSG:4326'
  dataStoreName.value = ''
}
watch(
  () => dialogVisible.value,
  () => {
    if (dialogVisible.value) {
    }
  },
  {
    immediate: true,
  },
)
onBeforeMount(() => {
  // 此处执行一次后确保 workspaceList 有值
  workspaceModal.getWorkspaceList()
})
onMounted(() => {
  workspaceModal.getDefaultWorkspace().then(() => {
    workspaceName.value = workspaceModal.defaultWorkspace.value.name
    workspaceChangeHandler()
  })
})
</script>

<style lang="scss">
.layer-publish-dialog {
  .el-dialog__body {
    padding: 10px 20px;
    .layer-info-scrollbar {
      max-height: 500px;
      .el-descriptions {
        .el-descriptions__header {
          margin-top: 6px;
          margin-bottom: 6px;
        }
      }
    }
  }
  .el-dialog__footer {
    padding: 10px 20px;
  }
}
</style>
